import {computed, ref} from "vue";
import {defineStore} from 'pinia';
import {getPlantQuarantineAPI} from "../../api/allAPI";
import {PlantItem} from "../../api/req";

export const usePlantStore = defineStore('PlantStore', () => {
    const plantSets = ref<PlantItem[]>([]);
    const loading = ref<boolean>(false);
    const plantPage = ref({
        currentPage: 1,
        total: 0,
        pageSize: 10,
        showSizePicker: true,
        pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
    });

    const updatePlantSets = async () => {
        loading.value = true;
        const req = {
            pageNo: plantPage.value.currentPage,
            pageSize: plantPage.value.pageSize,
        };

        const res = await getPlantQuarantineAPI(req);
        const { data, meta } = res.data;

        plantSets.value = data.map((item: any) => ({
            id: item.id,
            name: item.attributes.name,
            type: item.attributes.type || '',
            links: item.attributes.url ? [item.attributes.url] : [],
            date: item.attributes.time,
        }));
        plantPage.value.total = meta.pagination.total
        loading.value = false;
    };

    // 设置分页信息
    const setPlantSetsPage = (page?: number) => {
        if (page) plantPage.value.currentPage = page;
    };

    const getPlantSets = computed(() => {
        return plantSets.value;
    });

    const getPlantPage = computed(() => {
        return plantPage.value;
    });

    const pagination = computed(() => ({
        current: plantPage.value.currentPage,
        total: plantPage.value.total,
        pageSize: plantPage.value.pageSize,
        onChange: (page: number) => {
            setPlantSetsPage(page);
            updatePlantSets().then()
        },
    }));

    const getPlantLoading = computed(() => {
        return loading.value;
    });

    return {
        updatePlantSets,
        getPlantSets,
        setPlantSetsPage,
        getPlantPage,
        pagination,
        getPlantLoading
    }
})